package com.sxf.util.template;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jetbrick.io.resource.ResourceNotFoundException;
import jetbrick.template.JetEngine;
import jetbrick.template.JetGlobalContext;
import jetbrick.template.JetTemplate;
import jetbrick.template.web.JetWebContext;
import jetbrick.template.web.JetWebEngine;
import jetbrick.util.StringUtils;
import jetbrick.web.servlet.RequestUtils;

import org.springframework.util.Assert;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * 当SpringMVC和JetTemplateServlet共同使用
 * 
 * @author jiyi
 *
 */
public class JetTemplateServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private JetEngine engine;
	private String charsetEncoding;
	private Collection<HandlerInterceptorAdapter> handlers;

	@Override
	public void init() throws ServletException {
		engine = JetWebEngine.getEngine();
		Assert.notNull(engine);
		WebApplicationContext springContext = WebApplicationContextUtils
				.getWebApplicationContext(getServletContext());
		JetGlobalContext gc = engine.getGlobalContext();

		// 将Spring上下文放入JetBrick上下文
		gc.set("springContext", springContext);

		// 将hae.properties中的所有配置作为JetBrick的全局变量
		Map<String, String> props = new HashMap<String, String>();
		// .loadProperties(this.getClass()
		// .getResource("/hae.properties"));
		for (Map.Entry<String, String> e : props.entrySet()) {
			gc.set(e.getKey().replace('.', '_').toLowerCase(), e.getValue());
		}
		System.setProperty("dev.mode", props.get("dev.mode"));
		// 设置开发模式
		if ("true".equals(props.get("dev.mode"))) {
			gc.set("dev_mode", "-dev");
		} else {
			gc.set("min_js", ".min");
		}
		handlers = springContext
				.getBeansOfType(HandlerInterceptorAdapter.class).values();
		charsetEncoding = engine.getConfig().getOutputEncoding().name();
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setCharacterEncoding(charsetEncoding);
		if (response.getContentType() == null) {
			response.setContentType("text/html; charset=" + charsetEncoding);
		}
		String path = RequestUtils.getPathInfo(request);

		ModelAndView mov = new ModelAndView(path);
		for (HandlerInterceptorAdapter handler : handlers) {
			try {
				handler.preHandle(request, response, null);
				handler.postHandle(request, response, handler, mov);
			} catch (Exception e) {
				throw new ServletException(e);
			}
		}
		for (Map.Entry<String, Object> e : mov.getModelMap().entrySet()) {
			request.setAttribute(e.getKey(), e.getValue());
		}
		try {
			JetTemplate template = engine.getTemplate(path);
			JetWebContext context = new JetWebContext(request, response);
			template.render(context, response.getOutputStream());
		} catch (ResourceNotFoundException e) {
			response.sendError(HttpServletResponse.SC_NOT_FOUND,
					"Template not found: " + path);
		}
	}
}
